package com.nika.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import common.BaseResponse;
import common.ErrorCode;
import common.ResultUtils;
import com.nika.usercenter.exception.BusinessException;
import com.nika.usercenter.mapper.UserMapper;
import com.nika.usercenter.model.domain.User;
import com.nika.usercenter.model.request.UserLoginRequest;
import com.nika.usercenter.model.request.UserRegisterRequest;
import com.nika.usercenter.service.UserService;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.nika.usercenter.constant.UserConstant.USER_LOGIN_STATE;

//这个注解让返回值都是json形式
@Api(tags = "用户模块")
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private UserMapper userMapper;


    //requestbody在post请求下生效
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR, "对象为空");
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();

        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR, "参数为空");
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(result);
    }

    /**
     * session实现用户登录
     *
     * @param userLoginRequest
     * @param request
     * @param
     * @return
     */

    @PostMapping("/loginBySession")
    public BaseResponse<User> userLoginBySession(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR, "对象为空");
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();

        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR, "参数为空");
        }
        User user = userService.doLoginBySession(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    /**
     * token实现用户登录
     *
     * @param userLoginRequest
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/loginByToken")
    public BaseResponse<String> userLoginByToken(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request, HttpServletResponse response) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR, "对象为空");
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();

        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR, "参数为空");
        }

        String token = userService.doLoginByToken(userAccount, userPassword);
        return ResultUtils.success(token);
    }


    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        int result = userService.userLogOut(request);
        return ResultUtils.success(result);
    }

    @GetMapping("/currentBySession")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        User userObj = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN, "未登录取不到用户信息");
        }
        //因为可能存在session的信息的数据会变动
        User user = userService.getById(userObj.getId());
        User safetyUser = userService.getSafetyUser(user);
        return ResultUtils.success(safetyUser);
    }

    @GetMapping("/currentByToken")
    public BaseResponse<User> getCurrentUserByToken(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR);
        }
        User safetyUser = userService.getLoginUserByToken(request);
        return ResultUtils.success(safetyUser);
    }

    @GetMapping("/search")
    public BaseResponse<List<User>> searchUsers(String username, HttpServletRequest request) {
        //username可空
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN, "未登录取不到用户信息");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.eq("username", username);
        }
        List<User> users = userService.list(queryWrapper);
        List<User> result = users.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(result);
    }

    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody User user, HttpServletRequest request) {
        if (user == null || request == null) {
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        int result = userService.updateUser(user, loginUser);
        return ResultUtils.success(result);
    }

    @PostMapping("/updateByToken")
    public BaseResponse<Integer> updateUserByToken(@RequestBody User user, HttpServletRequest request) {
        if (user == null || request == null) {
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR);
        }
        User loginUser = userService.getLoginUserByToken(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        int result = userService.updateUser(user, loginUser);
        return ResultUtils.success(result);
    }


    @GetMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN, "未登录取不到用户信息");
        }
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "删除的用户id小于0，不存在");
        }
        boolean result = userService.removeById(id);
        return ResultUtils.success(result);
    }


    @GetMapping("/search/tags")
    public BaseResponse<List<User>> searchUsersByTags(@RequestParam(required = false) List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR);
        }
        List<User> users = userService.searchUsersByTags(tagNameList);
        return ResultUtils.success(users);
    }

    @GetMapping("/recommend")
    public BaseResponse<Object> recommendUsers(long pageSize, long pageNum, HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR, "request 对象为空");
        }
        Object userPage = userService.getRecommendFromCache(pageSize, pageNum, request);
        return ResultUtils.success(userPage);
    }

    @GetMapping
    public BaseResponse<List<User>> match(long num, HttpServletRequest request) {
        if (num <= 0 || num > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求人数过多");
        }
        User loginUser = userService.getLoginUser(request);
        List<User> matchUsers = userService.matchUsers(num,loginUser);
        return null;
    }


}
